﻿using MvcFileUploader;
using MvcFileUploader.HtmlHelper;
using MvcFileUploader.Models;
using SAIM.Models;
using SAIM.Models.BLL;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace SAIM.Controllers
{

    [Authorize]
    public class SocialServiceController : Controller
    {

        private SAIMIdentity UserIdentity
        {
            get { return new SAIMIdentity(User.Identity); }
        }
        // GET: SocialService
        public ActionResult Index(string id)
        {
            if (id != null)
            {
                using (SocialServiceBLL item = new SocialServiceBLL())
                {
                    return View(item.GetInformation(id));
                }
            }
            else
            {
                return View();
            }
        }

        [HttpPost]
        public ActionResult UpdateProgress(SocialServiceViewModel model)
        {
            using(SocialServiceBLL item = new SocialServiceBLL())
            {
                item.Update(model);
            }
            return new JsonResult()
            {
                Data = "Success"
            };
        }

        [HttpPost]
        public ActionResult Index(SocialServiceViewModel model)
        {
            return View();
        }

        [HttpGet]
        public ActionResult Manage()
        {
            return View();
        }

        public ActionResult SocialServiceStudents(int current, int rowCount, Dictionary<object, string> sort, string searchPhrase)
        {
            int _current = current;
            int _rowCount = rowCount;

            using (SocialServiceBLL item = new SocialServiceBLL())
            {
                return new JsonResult()
                {
                    Data = item.GetStudents(current, rowCount, sort, searchPhrase)
                };
            }
        }
        /*
        [HttpPost]
        public ActionResult UploadFile(string documentType)
        {
            return View();
        }
        */
        
        //--------------------------------------------Se ejecuta cuando se va descargar un archivo.------------------------------------------------
        public ActionResult GetAttachedFile(string id, string typeDocument)
        {
            long ticketId;
            string filePath, fileName;

            filePath = fileName = string.Empty;
            if ((id == null) || !long.TryParse(id, out ticketId))
                throw new HttpException(404, "Page Not Found");
            switch (typeDocument)
            {
                case"CartaAsignacion":
                    using (SocialServiceBLL attachment = new SocialServiceBLL())
                    {
                        attachment.GetAttachmentName(ticketId, typeDocument, ref filePath, ref fileName);

                        if (fileName == null)
                            throw new HttpException(404, "Archivo aun no cargado");

                      
                    }
                    break;

                case "CartaAceptacion":
                    using (SocialServiceBLL attachment = new SocialServiceBLL())
                    {
                        attachment.GetAttachmentName(ticketId, typeDocument, ref filePath, ref fileName);

                        if (fileName == null)
                            throw new HttpException(404, "Archivo aun no cargado");

                        
                    }
                    break;


                case "SeguroMedico":
                    using (SocialServiceBLL attachment = new SocialServiceBLL())
                    {
                        attachment.GetAttachmentName(ticketId, typeDocument, ref filePath, ref fileName);

                        if (fileName == null)
                            throw new HttpException(404, "Archivo aun no cargado");

                    }
                    break;
             
                default:
                    break;
            }
            return File(Path.Combine(filePath + "\\" + fileName), "multipart/form-data", fileName);
           
        }
        //----------------------------------------Se ejecuta cuando se carga un archivo con el MVCUPLOADER-------------------------------------------------------------------------------------------------

        [HttpPost]
        public ActionResult UploadFile(long? entityId, string StudentName,string tipoDeDocumento) // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url 
            var statuses = new List<ViewDataUploadFileResult>();
            string pathForSaving = Server.MapPath("~/Content/uploads/SocialService/SocialService_" + entityId + "_" + StudentName);

            if (entityId == null)
            {
                throw new HttpException(404, "Id required");
            }
            // Si no existe el directorio del usuario lo crea
            if (!CreateFolderIfNeeded(pathForSaving))
                throw new HttpException(404, "Can not create file");

            for (var i = 0; i < Request.Files.Count; i++)
            {

                using (SocialServiceBLL attachment = new SocialServiceBLL())
                {
                    MvcFileUploader.Models.ViewDataUploadFileResult st = null;                    
                    var myFile = Request.Files[i];                    
                    string nomArch = myFile.FileName.ToUpper();                                                            
                    //En esta funcion se inserta en el servidor y en la base de datos
                    //regresa un dato que si marca error es por que hubo algo mal.
                    switch (tipoDeDocumento)
                    {
                        case"CartaDeAceptacion":
                            st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(), "CartaDeAceptacion"); 
                            break;
                        case "CartaDeAsignacion":
                            st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(), "CartaDeAsignacion");
                            break;
                        case "SeguroMedico":
                            st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(), "SeguroMedico");
                            break;

                        default:
                            break;
                    }

                    if (st.error == null)//Si no existio Error
                    {
                        statuses.Add(st);

                    }

                }

            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            var viewresult = Json(new { files = statuses });
            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
                viewresult.ContentType = "text/plain";

            return viewresult;
        }



        [HttpPost]
        public ActionResult UploadFileCartaDeAceptacion(long? entityId) // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url 
            var statuses = new List<ViewDataUploadFileResult>();
            string pathForSaving = Server.MapPath("~/Content/uploads/SocialService/SocialService_" + UserIdentity.GetUserId());

            if (entityId == null)
            {
                throw new HttpException(404, "Id required");
            }
            // Si no existe el directorio del usuario lo crea
            if (!CreateFolderIfNeeded(pathForSaving))
                throw new HttpException(404, "Can not create file");

            for (var i = 0; i < Request.Files.Count; i++)
            {

                using (SocialServiceBLL attachment = new SocialServiceBLL())
                {
                    var myFile = Request.Files[i];
                    //En esta funcion se inserta en el servidor y en la base de datos
                    //regresa un dato que si marca error es por que hubo algo mal.
                    var st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(),"CartaDeAceptacion");
                    if (st.error == null)
                    {
                        statuses.Add(st);
                      
                    }
                 
                }
               
            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            var viewresult = Json(new { files = statuses });
            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
                viewresult.ContentType = "text/plain";

            return viewresult;
        }


        [HttpPost]
        public ActionResult UploadFileCartaDeAsignacion(long? entityId,string type) // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url 
            var statuses = new List<ViewDataUploadFileResult>();
            string pathForSaving = Server.MapPath("~/Content/uploads/SocialService/SocialService_" + UserIdentity.GetUserId());

            if (entityId == null)
            {
                throw new HttpException(404, "Id required");
            }
            // Si no existe el directorio del usuario lo crea
            if (!CreateFolderIfNeeded(pathForSaving))
                throw new HttpException(404, "Can not create file");

            for (var i = 0; i < Request.Files.Count; i++)
            {

                using (SocialServiceBLL attachment = new SocialServiceBLL())
                {
                    var myFile = Request.Files[i];
                    //En esta funcion se inserta en el servidor y en la base de datos
                    //regresa un dato que si marca error es por que hubo algo mal.
                    var st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(), "CartaDeAsignacion");
                    if (st.error == null)
                    {
                        statuses.Add(st);

                    }

                }

            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            var viewresult = Json(new { files = statuses });
            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
                viewresult.ContentType = "text/plain";

            return viewresult;
        }

        [HttpPost]
        public ActionResult UploadFileSeguroMedico(long? entityId) // optionally receive values specified with Html helper
        {
            // here we can send in some extra info to be included with the delete url 
            var statuses = new List<ViewDataUploadFileResult>();
            string pathForSaving = Server.MapPath("~/Content/uploads/SocialService/SocialService_" + UserIdentity.GetUserId());

            if (entityId == null)
            {
                throw new HttpException(404, "Id required");
            }
            // Si no existe el directorio del usuario lo crea
            if (!CreateFolderIfNeeded(pathForSaving))
                throw new HttpException(404, "Can not create file");

            for (var i = 0; i < Request.Files.Count; i++)
            {

                using (SocialServiceBLL attachment = new SocialServiceBLL())
                {
                    var myFile = Request.Files[i];
                    //En esta funcion se inserta en el servidor y en la base de datos
                    //regresa un dato que si marca error es por que hubo algo mal.
                    var st = attachment.AttachFileSocialService(myFile, entityId.ToString(), pathForSaving.ToString(), "SeguroMedico");
                    if (st.error == null)
                    {
                        statuses.Add(st);

                    }

                }

            }

            //statuses contains all the uploaded files details (if error occurs then check error property is not null or empty)
            //todo: add additional code to generate thumbnail for videos, associate files with entities etc

            //adding thumbnail url for jquery file upload javascript plugin
            statuses.ForEach(x => x.thumbnailUrl = x.url + "?width=80&height=80"); // uses ImageResizer httpmodule to resize images from this url

            //setting custom download url instead of direct url to file which is default
            statuses.ForEach(x => x.url = Url.Action("DownloadFile", new { fileUrl = x.url, mimetype = x.type }));

            var viewresult = Json(new { files = statuses });
            //for IE8 which does not accept application/json
            if (Request.Headers["Accept"] != null && !Request.Headers["Accept"].Contains("application/json"))
                viewresult.ContentType = "text/plain";

            return viewresult;
        }

        /// <summary>
        /// Creates the folder if needed.
        /// </summary>
        /// <param name="path">The path.</param>
        /// <returns></returns>
        private bool CreateFolderIfNeeded(string path)
        {
            bool result = true;
            if (!Directory.Exists(path))
            {
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception)
                {
                    result = false;
                }
            }
            return result;
        }



    }
}